import {createRouter, createWebHistory} from 'vue-router'
import Layout from "@/views/layout/Layout.vue";
import store from "@/store/index.js"

const routes = [
    {
        path: "/login",
        name: "login",
        component: () => import("@/views/pages/login.vue")
    },
    {
        path: '/',
        name: 'layout',
        component: Layout,
        redirect: "/welcome",
        //子路由或嵌套路由
        children: [
            {
                path: "/welcome",
                name: "welcome",
                component: () => import("@/views/welcome.vue")
            },
            {
                path: "/users",
                name: "users",
                component: () => import("@/views/pages/roles/users.vue")
            },
            {
                path: "/roles",
                name: "roles",
                component: () => import("@/views/pages/roles/roles.vue")
            }
        ]
    },
]

const router = createRouter({
    history: createWebHistory(process.env.BASE_URL),
    routes
})

router.beforeEach((to, from, next) => {
    /**
     * to:从哪个页面
     * from:到哪个页面
     * next:只有执行next()页面才会进行操作
     */
    //判断用户是否登录
    console.log("store", store.state.uInfo)
    const uInfo = store.state.uInfo.userInfo;
    if (!uInfo.token) {
        //未登录，跳转到login页面
        if (to.path ==="/login"){
            next();
            return;
        }
        next("/login")
    } else {
        //已登录
        next()
    }
})

export default router
